package com.sec.android.app.myfiles.module.trash;

import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.samsung.android.sdk.slinkcloud.CloudGatewayFileBrowserUtils;
import com.sec.android.app.myfiles.R;
import com.sec.android.app.myfiles.dialog.ConfirmEmptyTrashDialog;
import com.sec.android.app.myfiles.facade.MyFilesFacade;
import com.sec.android.app.myfiles.facade.cmd.SpinnerProgressCmd;
import com.sec.android.app.myfiles.feature.CloudMgr;
import com.sec.android.app.myfiles.fragment.AbsMyFilesFragment;
import com.sec.android.app.myfiles.info.AppConstants;
import com.sec.android.app.myfiles.log.SamsungAnalyticsLog;
import com.sec.android.app.myfiles.module.abstraction.AbsMenuImp;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.module.cloud.CloudFileOperationImp;
import com.sec.android.app.myfiles.navigation.NavigationInfo;
import com.sec.android.app.myfiles.navigation.NavigationManager;
import com.sec.android.app.myfiles.operation.FileOperator;
import com.sec.android.app.myfiles.util.StorageMonitor;
import com.sec.android.app.myfiles.util.UiUtils;

import java.util.ArrayList;


/**
 * Created by gw8951.kim on 2016-11-10.
 */

public class TrashFileMenuImp extends AbsMenuImp {
    public TrashFileMenuImp(Context context, FileRecord.StorageType supportStorage) {
        super(context, supportStorage);
    }

    @Override
    public void onPrepareNormalOptionsMenu(Menu menu) {
        super.onPrepareNormalOptionsMenu(menu);

        MenuItem menuItem = menu.findItem(R.id.menu_edit);
        if (menuItem != null) {
            menuItem.setShowAsAction(menuItem.SHOW_AS_ACTION_IF_ROOM);

            menu.setGroupVisible(R.id.menu_group_list, false);

            setMenuItemVisibility(menu, R.id.menu_edit, mListItemCount > 0);
            setMenuItemVisibility(menu, R.id.menu_create_folder, false);
            setMenuItemVisibility(menu, R.id.menu_sort_by, false);
            setMenuItemVisibility(menu, R.id.menu_show_hidden_files, false);
            setMenuItemVisibility(menu, R.id.menu_hide_hidden_files, false);
            setMenuItemVisibility(menu, R.id.menu_settings, false);
            setMenuItemVisibility(menu, R.id.menu_empty, mListItemCount > 0);
            setMenuItemVisibility(menu, R.id.menu_search, false);
            setMenuItemVisibility(menu, R.id.menu_toggle_list_type, false);
            setMenuItemEnabled(menu, R.id.menu_toggle_list_type, false);
        }
    }

    @Override
    public void onPrepareEditOptionsMenu(Menu menu) {
        int selectedCount;
        if (mFragment != null) {
            selectedCount = mFragment.getSelectedFileCount();
            setMenuItemVisibility(menu, R.id.menu_restore, selectedCount > 0);
            setMenuItemVisibility(menu, R.id.menu_delete, selectedCount > 0);
        }
    }


    @Override
    protected boolean _onOptionsItemSelected(MenuItem item) {
        boolean bRet = true;
        int id = item.getItemId();

        if (canExecute(id)) {
            int processId = mFragment.getProcessId();
            NavigationInfo info = NavigationManager.getInstance(processId).getCurInfo();
            if (info != null) {
                FileRecord curRecord = info.getCurRecord();
                int deviceId = getDeviceId(curRecord);
                switch (id) {
                    case R.id.menu_empty:
                        SamsungAnalyticsLog.sendLog(processId, SamsungAnalyticsLog.Event.EMPTY, null);
                        emptyTrash(deviceId, mFragment.getTotalFileCount());
                        bRet = true;
                        break;
                    case R.id.menu_restore:
                        SamsungAnalyticsLog.sendLog(processId, SamsungAnalyticsLog.Event.RESTORE, null);
                        restoreTrash();
                        bRet = true;
                        break;
                    default:
                        bRet = super._onOptionsItemSelected(item);
                        break;
                }
            }
        }
        return bRet;
    }

    private boolean canExecute(int id) {
        boolean canWithNetwork = (id == R.id.menu_empty) || (id == R.id.menu_restore) || (id == R.id.menu_delete);
        return !canWithNetwork || UiUtils.canExecuteCloud(mActivity, mFragment.getFragmentManager());
    }

    private int getDeviceId(FileRecord record) {
        int deviceId = 0;
        if (record instanceof TrashFileRecord) {
            TrashFileRecord trashRecord = (TrashFileRecord) record;
            deviceId = trashRecord.getDeviceId();
            if (deviceId <= 0) {
                if (TextUtils.equals(AppConstants.StoragePath.SAMSUNG_DRIVE_TRASH_FILES, trashRecord.getFullPath())) {
                    deviceId = CloudMgr.getInstance(mContext).getDeviceId(FileRecord.CloudType.SamsungDrive);
                }
            }
        }
        return deviceId;
    }


    private void emptyTrash(int deviceId, int listCount) {
        if (NavigationManager.isPossibleToActionMode()) {
            ConfirmEmptyTrashDialog dialog = new ConfirmEmptyTrashDialog();
            dialog.setArguments(getArgsEmptyTrash(deviceId, listCount));
            dialog.setTargetFragment(mFragment, R.id.menu_empty);

            if (mFragment != null && mFragment.getFragmentManager() != null) {
                FragmentTransaction ft = mFragment.getFragmentManager().beginTransaction();
                Fragment prev = mFragment.getFragmentManager().findFragmentByTag("confirm_empty_trash");
                if (prev != null) {
                    ft.remove(prev);
                }
                if (ft != null) {
                    ft.add(dialog, "confirm_empty_trash");
                    ft.commitAllowingStateLoss();
                }
            }
        } else {
            Toast.makeText(mContext, R.string.another_process_is_already_in_progress, Toast.LENGTH_LONG).show();
        }
    }

    private Bundle getArgsEmptyTrash(int deviceId, int listCount) {
        Bundle args = new Bundle();
        args.putInt(ConfirmEmptyTrashDialog.ARGS_DEVICE_ID, deviceId);
        args.putInt(ConfirmEmptyTrashDialog.ARGS_LIST_ITEMS_COUNT, listCount);

        return args;
    }

    private void restoreTrash() {
        final ArrayList<FileRecord> srcRecordList = mFragment.getSelectedFile();
        MyFilesFacade.execSpinnerProgress(mFragment.getProcessId(), mContext, SpinnerProgressCmd.OperationProgress.SHOW);
        Thread executeRestoreTrash = new Thread() {
            @Override
            public void run() {
                if (srcRecordList != null && !srcRecordList.isEmpty()) {
                    String[] sourceIdArr = new String[srcRecordList.size()];
                    int deviceId = ((TrashFileRecord) srcRecordList.get(0)).getDeviceId();
                    int index = 0;
                    for (FileRecord rec : srcRecordList) {
                        String fileId = ((TrashFileRecord) rec).getFileId();
                        sourceIdArr[index++] = fileId;
                    }
                    CloudGatewayFileBrowserUtils.getInstance(mContext).mrrControlBatchCommand(deviceId, CloudGatewayFileBrowserUtils.REMOTE_TRASH_RESTORE_BATCH, sourceIdArr, mQuotaCallback);
                    MyFilesFacade.execSpinnerProgress(mFragment.getProcessId(), mContext, SpinnerProgressCmd.OperationProgress.DISMISS);
                }
            }
        };
        executeRestoreTrash.start();
    }

    @Override
    public void createContextualMenu(ContextMenu menu, AbsMyFilesFragment fragment, FileRecord record) {
    }

    @Override
    public boolean _onContextualItemSelected(MenuItem item, ArrayList<FileRecord> srcRecordList, FileRecord record, AbsMyFilesFragment fragment) {
        return false;
    }

    private CloudGatewayFileBrowserUtils.QuotaError mQuotaCallback = new CloudGatewayFileBrowserUtils.QuotaError() {
        @Override
        public void onQuotaError(int errType, int nCmd) {
            FileOperator.Operation op = FileOperator.Operation.NONE;
            int resId = -1;
            switch (nCmd) {
                case CloudGatewayFileBrowserUtils.REMOTE_TRASH_RESTORE_BATCH:
                    op = FileOperator.Operation.RESTORE;
                    break;
                default:
                    break;
            }

            if (!op.equals(FileOperator.Operation.NONE)) {
                resId = CloudFileOperationImp.getResIdQuotaError(errType);
            }

            MyFilesFacade.showNotEnoughStorage(mFragment.getProcessId(), mContext, mFragment.getFragmentManager(), mFragment.getSelectedFile(),
                    String.format(mContext.getString(resId),
                            StorageMonitor.getDisplayName(mContext, AppConstants.StoragePath.SAMSUNG_DRIVE_FOLDER)),
                    FileOperator.Operation.RESTORE);
        }
    };
}
